/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormFabricacao.java
 *
 * Created on 03/11/2011, 15:38:24
 */
package javalee.forms;

import com.sun.rowset.CachedRowSetImpl;
import java.awt.print.PrinterException;
import java.io.IOException;
import javalee.util.Calculos;
import javalee.dao.ProdutoDAO;
import java.sql.ResultSet;
import javalee.maps.Produto;
import javalee.util.ExportaCSV;
import javax.sql.rowset.CachedRowSet;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author will
 */
public class FormFabricacao extends javax.swing.JFrame {

    private Calculos calcFabricacao;
    
    /** Creates new form FormFabricacao */
    public FormFabricacao() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbProducao = new javax.swing.JTable();
        javax.swing.text.MaskFormatter mf = null;
        try {
            mf = new javax.swing.text.MaskFormatter("##/##/####");
        } catch (java.text.ParseException p) {
            p.printStackTrace();
        }
        txtData = new javax.swing.JFormattedTextField(mf);
        jLabel1 = new javax.swing.JLabel();
        btnImprimir = new javax.swing.JButton();
        btnImprimir1 = new javax.swing.JButton();

        setTitle("Ordem de Fabricação");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        tbProducao.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Produto", "Quantidade", "Data"
            }
        ));
        jScrollPane1.setViewportView(tbProducao);

        txtData.setEditable(false);
        txtData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(mf,mf));
        txtData.setText("01/01/2012");
        txtData.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDataFocusLost(evt);
            }
        });

        jLabel1.setText("Data Início:");

        btnImprimir.setText("Imprimir");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        btnImprimir1.setText("Exportar CSV");
        btnImprimir1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimir1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 149, Short.MAX_VALUE)
                        .addComponent(btnImprimir1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnImprimir)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(btnImprimir)
                    .addComponent(btnImprimir1))
                .addContainerGap(39, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void txtDataFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDataFocusLost
    //ValidaData();
}//GEN-LAST:event_txtDataFocusLost

private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
    try{
    tbProducao.print();
    }catch(PrinterException e){
        e.printStackTrace();
    }
}//GEN-LAST:event_btnImprimirActionPerformed

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    
    calcFabricacao = new Calculos(); 
    
      Object[][] linhas = {{""}};
        Object[] colunas = { "ID", "Produto", "Semana 1", "Semana 2", "Semana 3", "Semana 4", "Semana 5"};
        DefaultTableModel Modelo = new DefaultTableModel(linhas, colunas);
        tbProducao.setModel(Modelo);
    
        try{
            CachedRowSet rsDemRev = new CachedRowSetImpl();
            rsDemRev.populate(calcFabricacao.demandaRevista());
              
            CachedRowSet rsProd = new CachedRowSetImpl();
            rsProd.populate(calcFabricacao.producaoRecalc(rsDemRev));
            
            CachedRowSet rsProdComposicao = new CachedRowSetImpl();
            rsProdComposicao.populate(calcFabricacao.buscaComposicao(rsProd));
            
            populaProducao(tbProducao, Modelo, rsProdComposicao);
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getCause());
            
        }
    
}//GEN-LAST:event_formWindowOpened

private void btnImprimir1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimir1ActionPerformed
    
      ExportaCSV Exportar = new ExportaCSV();
    
           try {
            Exportar.exportTable(tbProducao, "OrdensProducao.xls");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    
}//GEN-LAST:event_btnImprimir1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormFabricacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormFabricacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormFabricacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormFabricacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FormFabricacao().setVisible(true);
            }
        });
    }
    
          private void populaProducao(JTable tabela2, DefaultTableModel Modelo, ResultSet rs)
        {
            
            ProdutoDAO Produto = new ProdutoDAO();
            Produto Consulta;
            
            
        try {
            rs.first();
            do            
            {  
                if(!rs.getString("origem").equals("M"))
                {
                    Consulta = Produto.consultarPorId(rs.getInt("id_produto"));
                    
                    tabela2.setValueAt(rs.getInt("id_produto"), Modelo.getRowCount()-1, 0);
                    tabela2.setValueAt(Consulta.getDescricao(), Modelo.getRowCount()-1, 1);
                    for(int a = 1; a <= 5; a++)
                    {
                        tabela2.setValueAt(rs.getInt("qnt" + a), Modelo.getRowCount()-1, a+1);
                    }
                    Modelo.insertRow(Modelo.getRowCount(), new Object[] {""});
                   
                }

            }while(rs.next());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Preenche tabela " + ex.getMessage());
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnImprimir1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbProducao;
    private javax.swing.JFormattedTextField txtData;
    // End of variables declaration//GEN-END:variables
}
